﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using Ccit.Utils;
using System.Data;
using Ccit.ClassLibrary;
using Ccit.SysPlat.Log;

namespace Ccit.SysPlat.Organ
{
    /// <summary>
    /// Description: 系统平台组织机构 -> 机构管理SQL SERVER数据实现层
    /// Author: tim 2010-01-28
    /// </summary>
    public class OrganSQL : IOrgan
    {
        #region init error log interface
        private ILog _logInterface = null;
        private const string _funcPageName = "机构管理";
        public OrganSQL()
        {
            _logInterface = Factory.CreateObject(MsErrLog.assemblyName, MsErrLog.className, 
                                                    ImportComponentType.DotNetDll, null) as ILog;
        }        
        #endregion

        #region IOrgan 成员

        public MsOrgan GetOrganInfo(string organId)
        {
            StringBuilder sbCmdText = new StringBuilder();
            sbCmdText.Append("SELECT SYS_A4_10 AS ORGID,SYS_A4_20 AS ORGNAME,SYS_A4_30 AS ORGCODE,SYS_A4_40 AS LAYCODE,SYS_A4_50 AS ORGDESC,");
            sbCmdText.Append("SYS_A4_60 AS ORDERNO,SYS_A4_70 AS EFFECTSIGN FROM SYS_A4 WHERE SYS_A4_10='").Append(organId).Append("'");
            MsOrgan msOrgan = null;
            string _effectSign = string.Empty; //有效标志
            try
            {
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    if (iReader.Read() && null != iReader[0])
                    {
                        _effectSign = iReader["EFFECTSIGN"].ToString();
                        msOrgan = new MsOrgan
                        {
                            organId = iReader["ORGID"].ToString(),
                            organName = iReader["ORGNAME"].ToString(),
                            organCode = iReader["ORGCODE"].ToString(),
                            layCode = iReader["LAYCODE"].ToString(),
                            organDesc = iReader["ORGDESC"].ToString(),
                            orderNo = iReader["ORDERNO"].ToString(),
                            effectSign = _effectSign,
                            effectDesc = (_effectSign == "0") ? "有效" : "无效"
                        };
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            sbCmdText = null;
            return msOrgan;
        }

        public List<string> Save(MsOrgan msOrgan)
        {
            List<string> lstResult = null;

            string organId = msOrgan.organId;
            if (string.IsNullOrEmpty(organId))
                lstResult = addnew(msOrgan);
            else
                lstResult = update(msOrgan);

            return lstResult;
        }

        public string GetOrganNameById(string organId)
        {
            if (string.IsNullOrEmpty(organId)) return string.Empty;

            string organName = string.Empty;
            string cmdText = "SELECT SYS_A4_10 AS ORGID,SYS_A4_20 AS ORGNAME FROM SYS_A4 WHERE SYS_A4_10='" + organId + "'";
            try
            {
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    if (iReader.Read() && null != iReader[0])
                        organName = iReader["ORGNAME"].ToString();
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
            return organName;
        }

        public string GetOrganNamesByIds(string organIds, string separator, eTrueFalse isFilter)
        {
            if (string.IsNullOrEmpty(organIds)) return string.Empty;
                        
            string whereClause = (isFilter == eTrueFalse.TRUE) ? " AND SYS_A4_70='0'" : string.Empty;
            
            string organNames = getOrgNamesByIds(organIds, separator, whereClause);
            return organNames;
        }

        public string GetOrganNamesByIds(string organIds, string separator)
        {
            if (string.IsNullOrEmpty(organIds)) return string.Empty;

            string organNames = getOrgNamesByIds(organIds, separator, string.Empty);
            return organNames;
        }
        #endregion

        #region private methods

        private List<string> addnew(MsOrgan msOrgan)
        {
            //List<string> lstResult = null;
            //StringBuilder sbCmdText = new StringBuilder();
            //sbCmdText.Append("INSERT INTO SYS_A4 (SYS_A4_10,SYS_A4_20,SYS_A4_30,SYS_A4_40,SYS_A4_50,SYS_A4_60,SYS_A4_70) ");
            //sbCmdText.Append("SELECT (ISNULL(MAX(SYS_A4_10),0) + 1) NEWRECID,'");
            //sbCmdText.Append(msOrgan.organName.Replace("'", "''")).Append("','");
            //sbCmdText.Append(msOrgan.organCode.Replace("'", "''")).Append("','");
            //sbCmdText.Append("0001','");
            //sbCmdText.Append(msOrgan.organDesc.Replace("'", "''")).Append("','");
            //sbCmdText.Append("1','0' FROM SYS_A4");

            //int iexe = DataAccessor.ExecuteNonQuery(sbCmdText.ToString());
            //if (iexe > 0)
            //    lstResult = new List<string> {

            return new List<string> { "1", "保存成功!" };
        }


        private List<string> update(MsOrgan msOrgan)
        {
            List<string> lstResult = null;
            StringBuilder sbCmdText = new StringBuilder();
            string organId = msOrgan.organId;

            sbCmdText.Append("UPDATE SYS_A4 SET SYS_A4_20='").Append(msOrgan.organName.Replace("'", "''")).Append("',");
            sbCmdText.Append("SYS_A4_30='").Append(msOrgan.organCode.Replace("'", "''")).Append("',");
            sbCmdText.Append("SYS_A4_50='").Append(msOrgan.organDesc.Replace("'", "''")).Append("' ");
            sbCmdText.Append("WHERE SYS_A4_10='").Append(organId).Append("'");

            int iexe = 0;
            try {
                iexe = DataAccessor.ExecuteNonQuery(sbCmdText.ToString());
            }
            catch(Exception ex)
            {
                string className = ex.TargetSite.DeclaringType.ToString();
                string targetSit = ex.TargetSite.ToString();
                string message = ex.Message;
                string source = ex.Source;
                string memberType = ex.TargetSite.MemberType.ToString();
                string track = ex.StackTrace;
            }


            if (iexe > 0) lstResult = new List<string> { organId, "保存成功!" };
            else lstResult = new List<string> { "-1", "保存失败:详情请见错误日志!" };

            return lstResult;
        }


        private string getOrgNamesByIds(string organIds, string separator, string whereClause)
        {
            string cmdText = "SELECT SYS_A4_20 AS ORGNAME FROM SYS_A4 WHERE SYS_A4_10 IN (" + organIds + ") " + whereClause;
            string organName = string.Empty;
            string organNames = string.Empty;
            try {
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while (iReader.Read())
                    {
                        organName = iReader["ORGNAME"].ToString();
                        organNames += (string.IsNullOrEmpty(organNames)) ? organName : separator + organName;
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
            return organNames;
        }
        #endregion
        
    }
}
